/**
 * 企业微信机器人
 * @author LeoEatle
 * https://github.com/LeoEatle/git-webhook-wework-robot/blob/master/src/controller/chat.ts
 */
import { postData } from "./fetchUtil";
// 默认的企业微信机器人webhook地址
const defaultUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/";

export default class ChatRobot {
  constructor(robotId, options = {}) {
    this.robotId = robotId;
    if (options) {
      this.url = options.url || defaultUrl;
    }
  }

  /**
   * 向机器人webhook发出请求
   * @param json json信息
   */
  async sendHttpRequest(json) {
    console.log("http request", json);
    const url = `${this.url}send?key=${this.robotId}`;
    postData(url, json)
      .then(response => {
        if (response.statusCode == 200) {
          /* if (body.errcode === 0 && body.errmsg === "ok") {
            log.info("机器人成功发送通知" + body);
            return response;
          } else {
            console.error("机器人发送通知失败", body);
            throw body;
          } */
        } else {
          console.error("调用机器人webhook失败", error);
          throw error;
        }
      }) // JSON from `response.json()` call
      .catch(error => console.error(error));
    return;
  }

  /**
   * 发送文本消息
   * @param msg 文本信息
   * @param chatid 单独通知的群聊id，默认undefined
   * @param options 对应参数，请参考官方文档
   */
  async sendTextMsg(msg, chatid = undefined, options = {}) {
    const textMsgInfo = {
      msgtype: "text",
      chatid,
      text: {
        content: msg,
        ...options
      }
    };
    return await this.sendHttpRequest(textMsgInfo);
  }

  /**
   * 发送markdown信息
   * @param content Markdown内容
   * @param chatid 单独通知人手机号
   * @param options 其他参数，请参考官方文档
   */
  async sendMdMsg(content, mobileList = [], options = {}) {
    const markdownMsgInfo = {
      msgtype: "markdown",
      mentioned_mobile_list: mobileList,
      markdown: {
        content: content
      }
    };
    return await this.sendHttpRequest(markdownMsgInfo);
  }

  // TODO: 发送图文消息

  // TODO: 接受@消息

  // TODO: 获取群消息
}
